package system_smtp_log_dao

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/dao"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *SystemSmtpLog) FindSystemSmtpLogByCondition(ctx context.Context, page int, size int, options ...dao.SystemSmtpLogOption) (int64, []*model.SystemSmtpLog, errors.Error) {
	var session = cls.GetDb(ctx).Model(new(model.SystemSmtpLog))

	var metadata = dao.NewMetadata()
	for _, option := range options {
		var err errors.Error
		if session, err = option(session, metadata); nil != err {
			if err.IsType(errors.ErrorTypeRecordNotFound) {
				return 0, nil, nil
			}

			return 0, nil, err.Relation(errors.ErrorServerInternalError("IDSSL_OG.SSL_OG.FSSLBC_ON.220357", "配置选项失败"))
		}
	}

	var total int64
	if err := session.Count(&total).Error; nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSSL_OG.SSL_OG.FSSLBC_ON.200357 count failed, err %v", err)

		return 0, nil, errors.ErrorServerInternalError("IDSSL_OG.SSL_OG.FSSLBC_ON.300357", "统计数据失败")
	}

	if 0 == total || 0 == size || int64((page-1)*size) >= total {
		return total, nil, nil
	}

	var data []*model.SystemSmtpLog
	if err := session.Offset((page - 1) * size).Limit(size).Find(&data).Error; nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSSL_OG.SSL_OG.FSSLBC_ON.310357 find failed, err %v", err)

		return 0, nil, errors.ErrorServerInternalError("IDSSL_OG.SSL_OG.FSSLBC_ON.410357", "查询数据失败")
	}

	return total, data, nil
}
